import axios from 'axios';
import download from 'download-git-repo';
import { defaultConfig } from '../commands/config.js';

const { organization, token } = defaultConfig;

/**
 * 获取组织下的仓库项目
 * @returns
 */
export const getProject = async () => {
  const res = await axios.get(
    `https://gitee.com/api/v5/orgs/${organization}/repos`,
    {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    }
  );

  return res.data.map((item) => item.name);
};

/**
 * 获取分支
 * @param project
 * @returns
 */
export const getProjectBranch = async (project: string) => {
  const res = await axios.get(
    `https://gitee.com/api/v5/repos/${organization}/${project}/branches`,
    {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    }
  );
  return res.data.map((item) => item.name);
};

/**
 * 下载项目
 * @param project
 * @param branch
 */
export const downloadProject = async (project: string, branch: string) => {
  await download(
    `direct:https://gitee.com/xc_space/${project}.git/#${branch}`,
    `./${project}`,
    { clone: true },
    function (err) {
      console.log(err ? 'Error' : 'Success');
    }
  );
};
